<?php

class UserController extends Zend_Controller_Action
{
    /**
     * @return void
     */
    public function preDispatch()
    {
        $user = JFactory::getUser();
        $actionName = $this->_request->getActionName();
        switch ($actionName) {
            case 'login':
            case 'register':
                if (!$user->IsGuest) {
                    $this->redirect('/index/index');
                }
                break;
            case 'logout':
                if ($user->IsGuest) {
                    $this->redirect('/index/index');
                }
                break;
            case 'index':
                $this->redirect('/index/login');
                break;
        }
    }

    /**
     * @return void
     */
    public function init()
    {
    }

    /**
     * @return void
     */
    public function loginAction()
    {
        $this->view->messages = array();

        $isPost = $this->_request->getParam('isPost');
        if (isset($isPost)) {
            $username = $this->_request->getParam('username');
            $password = $this->_request->getParam('password');

            $authentication = JAuthentication::getInstance();
            $authentication->setRequiredInfo('Username', 'Password');
            $result = $authentication->authenticate($username, $password);
            switch ($result->getCode()) {
                case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                    $this->view->messages = array('Username Is Not Found');
                    $this->view->username = $username;
                    $this->view->password = $password;
                    break;
                case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                    $this->view->messages = array('Password Is Invalid');
                    $this->view->username = $username;
                    $this->view->password = $password;
                    break;
                case Zend_Auth_Result::SUCCESS:
                    $userID = Application_Model_User::getUserID($username);
                    $user = JUser::getInstance($userID);
                    JSession::setUser($user);
                    /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
                    $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                    $flashMessenger->addMessage('Login Successfully');
                    $this->redirect('/index/index');
                    break;
            }
        }
    }

    /**
     * @return void
     */
    public function registerAction()
    {
        $this->view->messages = array();

        $isPost = $this->_request->getParam('isPost');
        if (isset($isPost)) {
            $messages = array();
            $validInfo = true;

            $username = $this->_request->getParam('username');
            $email = $this->_request->getParam('email');
            $password = $this->_request->getParam('password');
            $realName = $this->_request->getParam('realName');
            $birthday = new Zend_Date($this->_request->getParam('birthday'));
            $mobilePhone = $this->_request->getParam('mobilePhone');
            $captchaWord = $this->_request->getParam('captchaWord');
            $captchaID = $this->_request->getParam('captchaID');

            $authentication = JAuthentication::getInstance();
            $authentication->setRequiredInfo('Username');
            $result = $authentication->authenticate($username);
            if ($result->getCode() == Zend_Auth_Result::SUCCESS) {
                array_push($messages, 'This Username Existed');
                $validInfo = false;
            }

            $authentication->setRequiredInfo('Email');
            $result = $authentication->authenticate($email);
            if ($result->getCode() == Zend_Auth_Result::SUCCESS) {
                array_push($messages, 'This Email Existed');
                $validInfo = false;
            }

            if ($captchaWord != JSession::getVar($captchaID)) {
                array_push($messages, 'Captcha Is Invalid');
                $validInfo = false;
            }

            if (!$validInfo) {
                $this->view->messages = $messages;
                $this->view->username = $username;
                $this->view->email = $email;
                $this->view->password = $password;
                $this->view->realName = $realName;
                $this->view->birthday = $birthday->get('d - M - y');
                $this->view->mobilePhone = $mobilePhone;
            } else {
                $userID = Application_Model_User::addUser(
                    $username, $email, $password, $realName,
                    $birthday, $mobilePhone
                );
                if ($userID == 0) {
                    $this->view->messages = array('Register Fail');
                    $this->view->username = $username;
                    $this->view->email = $email;
                    $this->view->password = $password;
                    $this->view->realName = $realName;
                    $this->view->birthday = $birthday->get('d - M - y');
                    $this->view->mobilePhone = $mobilePhone;
                } else {
                    $user = JFactory::getUser($userID);
                    JSession::setUser($user);

                    // BEGIN: Gửi mail xác nhận
                    $mail = new Zend_Mail();

                    $subject = 'Completed Your Registration';
                    $token = md5($username . $email . $password);
                    $confirmLink = "http://localhost/classico/public/user/confirm/userID/$userID/token/$token";
                    $bodyHtml = "Cám ơn bạn đã đăng ký tài khoản trên Classico Deal - mời bạn click
                                 vào link sau để xác nhận: <a href='$confirmLink'>Link xác nhận</a>";
                    $mail->addTo($email)
                        ->setSubject($subject)
                        ->setBodyHtml($bodyHtml);

                    $mail->send();
                    // END: Gửi mail xác nhận

                    /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
                    $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                    $flashMessenger->addMessage('Register Successfully');
                    $flashMessenger->addMessage('You Must Confirm To Sign Up An Order');
                    $this->redirect('/index/index');
                }
            }
        }

        $captcha = new Zend_Captcha_Image();

        $captcha->setWordlen('6');
        $captcha->setTimeout('300');
        $captcha->setWidth('400');
        $captcha->setHeight('80');
        $captcha->setImgDir(APPLICATION_PATH . '/../public/assets/trivial/captcha/images');
        $captcha->setImgUrl('/classico/public/assets/trivial/captcha/images');
        $captcha->setFont(APPLICATION_PATH . '/../public/assets/trivial/captcha/fonts/arial.ttf');
        $captcha->generate();
        $captchaID = $captcha->getId();
        $captchaWord = $captcha->getWord();

        JSession::setVar($captchaID, $captchaWord);

        $this->view->captcha = $captcha->render($this->view);
        $this->view->captchaID = $captchaID;
    }

    /**
     * @return void
     */
    public function confirmAction()
    {
        $userID = $this->_request->getParam('userID');
        $userPOJO = Application_Model_User::getUser($userID);
        $token = $this->_request->getParam('token');
        if (md5($userPOJO->Username . $userPOJO->Email . $userPOJO->Password) == $token) {
            $user = JFactory::getUser($userID);
            if ($user->confirm()) {
                /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
                $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                $flashMessenger->addMessage('Confirm Successfully');
                $this->redirect('/index/index');
            }
        }

        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $flashMessenger->addMessage('Confirm Successfully');
        $this->redirect('/index/index');
    }

    /**
     * @return void
     */
    public function logoutAction()
    {
        JSession::setShoppingCart(null);

        $user = JFactory::getUser();
        $user->updateLastLogout();
        JSession::setUser(null);

        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $flashMessenger->addMessage('Logout Successfully');
        $this->redirect('/index/index');
    }
}
